import { useState, useEffect, useRef } from 'react';

export default ({
  spaceTime,
  callback,
}: {
  /** @spaceTime 间隔时间：单位毫秒 */ spaceTime: number;
  /** @callback 每次间隔的回调 */ callback?: () => void;
}): {
  /** @time 计时次数 */ time: number;
  /** @stop 停止计时(重置) */ stop: () => void;
  /** @start 开始计时 */ start: () => void;
} => {
  const timer = useRef<any>(null);
  const [time, setTime] = useState(0);
  const [status, setStatus] = useState(false);
  const refresh = () =>
    (timer.current = setTimeout(() => {
      setTime(time + 1);
      if (callback) callback();
    }, spaceTime));

  useEffect(() => {
    if (!status) return;
    clearTimeout(timer.current);
    refresh();
  });

  useEffect(() => {
    if (status) {
      refresh();
    } else {
      clearTimeout(timer.current);
      setTime(0);
    }
  }, [status]);
  return {
    time,
    stop: () => setStatus(false),
    start: () => setStatus(true),
  };
};
